package com.company.genealogy.web.service.impl;

import com.company.genealogy.web.service.FamilyTreeService;
import com.company.genealogy.web.dto.TreeDragDTO;
import com.company.genealogy.web.dto.BatchMoveDTO;
import com.company.genealogy.web.dto.GenerationNameDTO;
import com.company.genealogy.web.entity.MemberSpouse;
import com.company.genealogy.web.mapper.BranchMapper;
import com.company.genealogy.web.mapper.MemberMapper;
import com.company.genealogy.web.mapper.MemberSpouseMapper;
import com.company.genealogy.web.vo.FamilyTreeNodeWithRelationVO;
import com.company.genealogy.web.vo.TimelineMemberVO;
import org.springframework.stereotype.Service;
import java.util.List;

import com.company.genealogy.web.entity.Member;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.stream.Collectors;

@Service
public class FamilyTreeServiceImpl implements FamilyTreeService {
    @Override
    public FamilyTreeNodeWithRelationVO getFamilyTreeWithRelation(Long clanId, Long branchId, Integer generation, Long rootMemberId) {
        Member root = null;
        if (rootMemberId != null) {
            root = memberMapper.selectById(rootMemberId);
        } else {
            QueryWrapper<Member> query = new QueryWrapper<>();
            query.eq("clan_id", clanId);
            if (branchId != null) query.eq("branch_id", branchId);
            if (generation != null) query.eq("generation", generation);
            query.isNull("father_id");
            query.orderByAsc("sort_order").last("limit 1");
            root = memberMapper.selectOne(query);
        }
        if (root == null) return null;
        return buildTreeNodeWithRelation(root, clanId, branchId, generation, "本人");
    }

    @Override
    public void dragMember(TreeDragDTO dto) {
        // TODO: 拖拽调整成员关系，更新父子/配偶/世代/lineage_path等
    }

    @Override
    public void batchMove(BatchMoveDTO dto) {
        // TODO: 批量移动成员及其子孙
    }

    @Override
    public List<TimelineMemberVO> getTimeline(Long clanId, Long branchId, Integer startYear, Integer endYear) {
        // TODO: 按出生/去世时间排序成员，时间轴模式
        return null;
    }

    @Override
    public void generateGenerationNames(GenerationNameDTO dto) {
        // TODO: 自动排辈字生成，批量更新成员generation_name
    }

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private MemberSpouseMapper memberSpouseMapper;

    private FamilyTreeNodeWithRelationVO buildTreeNodeWithRelation(Member member, Long clanId, Long branchId, Integer generation, String relationType) {
        FamilyTreeNodeWithRelationVO vo = new FamilyTreeNodeWithRelationVO();
        vo.setId(member.getId());
        vo.setName(member.getName());
        vo.setGender(member.getGender());
        vo.setGeneration(member.getGeneration());
        vo.setFatherId(member.getFatherId());
        vo.setMotherId(member.getMotherId());
        vo.setBranchId(member.getBranchId());
        vo.setPhoto(member.getPhoto());
        vo.setBranchName(member.getBranchName());
        vo.setFatherName(member.getFatherName());
        vo.setChildOrder(member.getChildOrder());
        vo.setRelationType(relationType);
        // 查询多配偶
        List<MemberSpouse> spouseRelations = memberSpouseMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MemberSpouse>().eq("member_id", member.getId())
        );
        List<FamilyTreeNodeWithRelationVO.SpouseVO> spouseList = spouseRelations.stream().map(rel -> {
            Member spouse = memberMapper.selectById(rel.getSpouseId());
            FamilyTreeNodeWithRelationVO.SpouseVO svo = new FamilyTreeNodeWithRelationVO.SpouseVO();
            if (spouse != null) {
                svo.setId(spouse.getId());
                svo.setName(spouse.getName());
                svo.setGender(spouse.getGender());
                svo.setPhoto(spouse.getPhoto());
            }
            svo.setRelationType(rel.getRelationType());
            svo.setSortOrder(rel.getSortOrder());
            return svo;
        }).collect(Collectors.toList());
        vo.setSpouseList(spouseList);
        // 查询子女，按childOrder排序
        QueryWrapper<Member> childQuery = new QueryWrapper<>();
        childQuery.eq("father_id", member.getId());
        childQuery.eq("clan_id", member.getClanId());
        childQuery.orderByAsc("child_order");
        List<Member> children = memberMapper.selectList(childQuery);
        List<FamilyTreeNodeWithRelationVO> childVOs = children.stream()
                .map(child -> buildTreeNodeWithRelation(child, clanId, branchId, generation, getChildRelationType(child)))
                .collect(Collectors.toList());
        vo.setChildren(childVOs);
        return vo;
    }

    private String getChildRelationType(Member child) {
        if (child.getGender() == null) return "子女";
        if (child.getChildOrder() != null && child.getChildOrder() == 1) {
            return "M".equals(child.getGender()) ? "长子" : "长女";
        }
        return "M".equals(child.getGender()) ? "儿子" : "女儿";
    }
} 